<template>
  <div class="exercises-container">
    <h1>练习题库</h1>
    
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-group">
        <label for="document-filter">文档:</label>
        <select id="document-filter" v-model="documentFilter" class="filter-select">
          <option value="">全部文档</option>
          <option v-for="doc in documents" :key="doc._id" :value="doc._id">
            {{ doc.title || doc.filename }}
          </option>
        </select>
      </div>
      
      <div class="filter-group">
        <label for="type-filter">题型:</label>
        <select id="type-filter" v-model="typeFilter" class="filter-select">
          <option value="">全部题型</option>
          <option value="MULTIPLE_CHOICE">选择题</option>
          <option value="FILL_BLANK">填空题</option>
          <option value="CODING">编程题</option>
        </select>
      </div>
      
      <div class="filter-group">
        <label for="difficulty-filter">难度:</label>
        <select id="difficulty-filter" v-model="difficultyFilter" class="filter-select">
          <option value="">全部难度</option>
          <option value="EASY">简单</option>
          <option value="MEDIUM">中等</option>
          <option value="HARD">困难</option>
        </select>
      </div>
      
      <div class="filter-group">
        <label for="status-filter">状态:</label>
        <select id="status-filter" v-model="statusFilter" class="filter-select">
          <option value="">全部状态</option>
          <option value="COMPLETED">已完成</option>
          <option value="INCOMPLETE">未完成</option>
          <option value="CORRECT">答对</option>
          <option value="INCORRECT">答错</option>
        </select>
      </div>
      
      <div class="filter-group search-group">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索练习题..." 
          class="search-input"
        />
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <p>加载中...</p>
    </div>
    
    <!-- 错误信息 -->
    <div v-if="error" class="error-message">
      {{ error }}
    </div>
    
    <!-- 空状态 -->
    <div v-if="!loading && !filteredExercises.length" class="empty-state">
      <p>没有找到符合条件的练习题</p>
      <button @click="generateExercises" class="btn-generate" :disabled="generating">
        {{ generating ? '生成中...' : '生成新练习题' }}
      </button>
    </div>
    
    <!-- 练习题列表 -->
    <div v-if="!loading && filteredExercises.length" class="exercises-grid">
      <div 
        v-for="exercise in filteredExercises" 
        :key="exercise._id" 
        class="exercise-item"
        :class="{
          'exercise-completed': exercise.status === 'COMPLETED',
          'exercise-correct': exercise.status === 'CORRECT',
          'exercise-incorrect': exercise.status === 'INCORRECT'
        }"
      >
        <div class="exercise-header">
          <span :class="['exercise-type', typeof exercise.type === 'string' ? exercise.type.toLowerCase() : '']">
            {{ getExerciseTypeText(exercise.type) }}
          </span>
          
          <span :class="['exercise-status', getStatusClass(exercise.status)]">
            {{ getStatusText(exercise.status) }}
          </span>
        </div>
        
        <div class="exercise-content">
          <h3>{{ truncateText(exercise.question, 100) }}</h3>
          
          <div class="exercise-meta">
            <span :class="['difficulty', typeof exercise.difficulty === 'string' ? exercise.difficulty.toLowerCase() : '']">
              {{ getDifficultyText(exercise.difficulty) }}
            </span>
            
            <span v-if="exercise.documentTitle" class="document-name" :title="exercise.documentTitle">
              {{ exercise.documentTitle }}
            </span>
          </div>
        </div>
        
        <div class="exercise-footer">
          <router-link :to="`/exercises/${exercise._id}`" class="btn-solve">
            {{ exercise.status === 'COMPLETED' || exercise.status === 'CORRECT' || exercise.status === 'INCORRECT' ? '重做' : '开始练习' }}
          </router-link>
          
          <router-link 
            v-if="exercise.cardId" 
            :to="`/cards/${exercise.cardId}`" 
            class="btn-view-card"
          >
            查看知识点
          </router-link>
        </div>
      </div>
    </div>
    
    <!-- 分页控件 -->
    <div v-if="totalPages > 1" class="pagination">
      <button 
        @click="changePage(currentPage - 1)" 
        :disabled="currentPage === 1"
        class="btn-page"
      >
        上一页
      </button>
      
      <span class="page-info">{{ currentPage }} / {{ totalPages }}</span>
      
      <button 
        @click="changePage(currentPage + 1)" 
        :disabled="currentPage === totalPages"
        class="btn-page"
      >
        下一页
      </button>
    </div>
    
    <!-- 生成练习题对话框 -->
    <div v-if="showGenerateModal" class="modal-overlay">
      <div class="modal-content">
        <h2>生成新练习题</h2>
        
        <form @submit.prevent="confirmGenerate">
          <div class="form-group">
            <label for="gen-document">选择文档</label>
            <select 
              id="gen-document" 
              v-model="generateForm.documentId" 
              class="form-select"
              required
            >
              <option value="" disabled>请选择文档</option>
              <option v-for="doc in documents" :key="doc._id" :value="doc._id">
                {{ doc.title || doc.filename }}
              </option>
            </select>
          </div>
          
          <div class="form-group">
            <label for="gen-count">生成数量</label>
            <input 
              type="number" 
              id="gen-count" 
              v-model.number="generateForm.count" 
              min="1" 
              max="10" 
              class="form-input"
              required
            />
          </div>
          
          <div class="form-group">
            <label for="gen-type">题型</label>
            <select 
              id="gen-type" 
              v-model="generateForm.type" 
              class="form-select"
            >
              <option value="">随机题型</option>
              <option value="MULTIPLE_CHOICE">选择题</option>
              <option value="FILL_BLANK">填空题</option>
              <option value="CODING">编程题</option>
            </select>
          </div>
          
          <div class="form-group">
            <label for="gen-difficulty">难度</label>
            <select 
              id="gen-difficulty" 
              v-model="generateForm.difficulty" 
              class="form-select"
            >
              <option value="">随机难度</option>
              <option value="EASY">简单</option>
              <option value="MEDIUM">中等</option>
              <option value="HARD">困难</option>
            </select>
          </div>
          
          <div class="modal-actions">
            <button type="button" @click="showGenerateModal = false" class="btn-cancel">
              取消
            </button>
            <button type="submit" class="btn-confirm" :disabled="generating">
              {{ generating ? '生成中...' : '生成' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { exerciseApi, documentApi } from '@/services/api';

const route = useRoute();
const router = useRouter();

// 状态变量
const loading = ref(false);
const error = ref('');
const exercises = ref([]);
const documents = ref([]);
const documentFilter = ref('');
const typeFilter = ref('');
const difficultyFilter = ref('');
const statusFilter = ref('');
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(12);
const totalExercises = ref(0);
const generating = ref(false);
const showGenerateModal = ref(false);
const generateForm = ref({
  documentId: '',
  count: 5,
  type: '',
  difficulty: ''
});

// 从路由参数获取初始筛选条件
onMounted(async () => {
  if (route.query.document) {
    documentFilter.value = route.query.document;
  }
  
  if (route.query.type) {
    typeFilter.value = route.query.type;
  }
  
  if (route.query.difficulty) {
    difficultyFilter.value = route.query.difficulty;
  }
  
  if (route.query.status) {
    statusFilter.value = route.query.status;
  }
  
  if (route.query.search) {
    searchQuery.value = route.query.search;
  }
  
  if (route.query.page) {
    currentPage.value = parseInt(route.query.page) || 1;
  }
  
  // 获取文档列表
  await fetchDocuments();
  
  // 获取练习题列表
  await fetchExercises();
});

// 监听筛选条件变化
watch([documentFilter, typeFilter, difficultyFilter, statusFilter, searchQuery], () => {
  // 重置页码
  currentPage.value = 1;
  
  // 更新路由参数
  updateRouteQuery();
  
  // 重新获取练习题
  fetchExercises();
});

// 监听页码变化
watch(currentPage, () => {
  // 更新路由参数
  updateRouteQuery();
  
  // 重新获取练习题
  fetchExercises();
});

// 计算属性
const filteredExercises = computed(() => exercises.value);

const totalPages = computed(() => {
  return Math.ceil(totalExercises.value / pageSize.value) || 1;
});

// 方法
const fetchExercises = async () => {
  loading.value = true;
  error.value = '';
  
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      limit: pageSize.value
    };
    
    if (documentFilter.value) {
      params.documentId = documentFilter.value;
    }
    
    if (typeFilter.value) {
      params.type = typeFilter.value;
    }
    
    if (difficultyFilter.value) {
      params.difficulty = difficultyFilter.value;
    }
    
    if (statusFilter.value) {
      params.status = statusFilter.value;
    }
    
    if (searchQuery.value) {
      params.search = searchQuery.value;
    }
    
    const response = await exerciseApi.getAll(params);
    exercises.value = response.data.exercises;
    totalExercises.value = response.data.total;
  } catch (err) {
    error.value = '获取练习题失败';
    console.error('获取练习题失败:', err);
  } finally {
    loading.value = false;
  }
};

const fetchDocuments = async () => {
  try {
    const response = await documentApi.getAll();
    documents.value = response.data;
  } catch (err) {
    console.error('获取文档列表失败:', err);
  }
};

const updateRouteQuery = () => {
  const query = {};
  
  if (documentFilter.value) {
    query.document = documentFilter.value;
  }
  
  if (typeFilter.value) {
    query.type = typeFilter.value;
  }
  
  if (difficultyFilter.value) {
    query.difficulty = difficultyFilter.value;
  }
  
  if (statusFilter.value) {
    query.status = statusFilter.value;
  }
  
  if (searchQuery.value) {
    query.search = searchQuery.value;
  }
  
  if (currentPage.value > 1) {
    query.page = currentPage.value;
  }
  
  router.replace({ query });
};

const changePage = (page) => {
  if (page < 1 || page > totalPages.value) return;
  currentPage.value = page;
};

const generateExercises = () => {
  showGenerateModal.value = true;
};

const confirmGenerate = async () => {
  if (!generateForm.value.documentId) return;
  
  generating.value = true;
  
  try {
    const params = {
      documentId: generateForm.value.documentId,
      count: generateForm.value.count
    };
    
    if (generateForm.value.type) {
      params.type = generateForm.value.type;
    }
    
    if (generateForm.value.difficulty) {
      params.difficulty = generateForm.value.difficulty;
    }
    
    await exerciseApi.generateBatch(params);
    
    // 重置表单
    generateForm.value = {
      documentId: '',
      count: 5,
      type: '',
      difficulty: ''
    };
    
    // 关闭对话框
    showGenerateModal.value = false;
    
    // 重新获取练习题
    await fetchExercises();
  } catch (err) {
    console.error('生成练习题失败:', err);
  } finally {
    generating.value = false;
  }
};

// 辅助函数
const getExerciseTypeText = (type) => {
  const typeMap = {
    'MULTIPLE_CHOICE': '选择题',
    'FILL_BLANK': '填空题',
    'CODING': '编程题'
  };
  
  return typeMap[type] || String(type);
};

const getDifficultyText = (difficulty) => {
  const difficultyMap = {
    'EASY': '简单',
    'MEDIUM': '中等',
    'HARD': '困难',
    1: '简单',
    2: '中等',
    3: '困难'
  };
  
  return difficultyMap[difficulty] || String(difficulty);
};

const getStatusText = (status) => {
  const statusMap = {
    'INCOMPLETE': '未完成',
    'COMPLETED': '已完成',
    'CORRECT': '答对',
    'INCORRECT': '答错'
  };
  
  return statusMap[status] || String(status);
};

const getStatusClass = (status) => {
  const classMap = {
    'INCOMPLETE': 'status-incomplete',
    'COMPLETED': 'status-completed',
    'CORRECT': 'status-correct',
    'INCORRECT': 'status-incorrect'
  };
  
  return classMap[status] || '';
};

const truncateText = (text, maxLength) => {
  if (!text) return '';
  
  if (text.length <= maxLength) {
    return text;
  }
  
  return text.substring(0, maxLength) + '...';
};
</script>

<style scoped>
.exercises-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

h1 {
  margin-bottom: 2rem;
  color: #333;
}

/* 筛选区域样式 */
.filter-section {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  margin-bottom: 2rem;
  padding: 1.5rem;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.filter-group {
  display: flex;
  flex-direction: column;
  min-width: 150px;
}

.search-group {
  flex-grow: 1;
}

.filter-group label {
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #555;
}

.filter-select, .search-input {
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 0.9rem;
}

.filter-select:focus, .search-input:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

/* 加载和错误状态样式 */
.loading-container, .empty-state {
  text-align: center;
  padding: 3rem;
  background-color: #f9f9f9;
  border-radius: 8px;
  color: #666;
}

.error-message {
  color: #ff3860;
  background-color: #feecf0;
  padding: 1rem;
  border-radius: 4px;
  margin-bottom: 1rem;
}

.btn-generate {
  padding: 0.75rem 1.5rem;
  background-color: #FF9800;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 1rem;
}

.btn-generate:hover {
  background-color: #F57C00;
}

.btn-generate:disabled {
  background-color: #9e9e9e;
  cursor: not-allowed;
}

/* 练习题网格样式 */
.exercises-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.exercise-item {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 1.5rem;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.exercise-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.exercise-completed {
  border-left: 4px solid #9C27B0;
}

.exercise-correct {
  border-left: 4px solid #4CAF50;
}

.exercise-incorrect {
  border-left: 4px solid #F44336;
}

.exercise-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.exercise-type {
  padding: 0.25rem 0.5rem;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 500;
}

.exercise-type.multiple_choice {
  background-color: #e3f2fd;
  color: #1976d2;
}

.exercise-type.fill_blank {
  background-color: #fff8e1;
  color: #ff8f00;
}

.exercise-type.coding {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.exercise-status {
  font-size: 0.75rem;
  font-weight: 500;
}

.status-incomplete {
  color: #757575;
}

.status-completed {
  color: #9C27B0;
}

.status-correct {
  color: #4CAF50;
}

.status-incorrect {
  color: #F44336;
}

.exercise-content {
  flex: 1;
}

.exercise-content h3 {
  margin-top: 0;
  margin-bottom: 1rem;
  color: #333;
  font-size: 1.1rem;
  line-height: 1.5;
}

.exercise-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  margin-bottom: 1rem;
}

.difficulty {
  padding: 0.25rem 0.5rem;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 500;
}

.difficulty.easy {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.difficulty.medium {
  background-color: #fff8e1;
  color: #ff8f00;
}

.difficulty.hard {
  background-color: #ffebee;
  color: #c62828;
}

.document-name {
  font-size: 0.8rem;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 150px;
}

.exercise-footer {
  display: flex;
  gap: 0.75rem;
  margin-top: 1rem;
}

.btn-solve, .btn-view-card {
  padding: 0.5rem;
  border-radius: 4px;
  font-size: 0.9rem;
  cursor: pointer;
  text-align: center;
  flex: 1;
  text-decoration: none;
}

.btn-solve {
  background-color: #4CAF50;
  color: white;
  border: none;
}

.btn-solve:hover {
  background-color: #388E3C;
}

.btn-view-card {
  background-color: #2196F3;
  color: white;
  border: none;
}

.btn-view-card:hover {
  background-color: #1976D2;
}

/* 分页控件样式 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1rem;
  margin-top: 2rem;
}

.btn-page {
  padding: 0.5rem 1rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
  cursor: pointer;
}

.btn-page:hover:not(:disabled) {
  background-color: #f0f0f0;
}

.btn-page:disabled {
  color: #999;
  cursor: not-allowed;
}

.page-info {
  color: #666;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 2rem;
  border-radius: 8px;
  max-width: 500px;
  width: 90%;
}

.modal-content h2 {
  margin-top: 0;
  margin-bottom: 1.5rem;
  color: #333;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
}

.form-select, .form-input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.form-select:focus, .form-input:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1.5rem;
}

.btn-cancel, .btn-confirm {
  padding: 0.75rem 1.5rem;
  border-radius: 4px;
  cursor: pointer;
}

.btn-cancel {
  background-color: transparent;
  color: #333;
  border: 1px solid #ddd;
}

.btn-confirm {
  background-color: #FF9800;
  color: white;
  border: none;
}

.btn-confirm:hover {
  background-color: #F57C00;
}

.btn-confirm:disabled {
  background-color: #9e9e9e;
  cursor: not-allowed;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .filter-section {
    flex-direction: column;
    gap: 1rem;
  }
  
  .filter-group {
    width: 100%;
  }
  
  .exercises-grid {
    grid-template-columns: 1fr;
  }
}
</style> 